package com.easyUploader.entity.dao;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;

import java.io.File;
import java.io.Serializable;
import java.time.LocalDateTime;
import com.easyUploader.property.LocalFileProperty;
import com.easyUploader.threadHolder.UserThreadHolder;
import com.easyUploader.util.FileUtil;
import com.easyUploader.util.ZipUtil;
import lombok.AllArgsConstructor;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

/**
 * @author 大忽悠
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
@Slf4j
public class Bucket implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * ID
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    /**
     * 存储桶名称
     */
    private String name;

    /**
     * 存储桶类型: 0-只读,1-读写
     */
    private Integer bucketType;

    /**
     * 访问类型: 0-私有,1-公开
     */
    private Integer accessType;

    /**
     * 创建者id
     */
    private Integer createBy;

    /**
     * 更新者id
     */
    private Integer updateBy;

    /**
     * 是否是系统资源: 0-不是,1-是
     */
    private Integer system;

    /**
     * 存储桶下的文件数量
     */
    private Integer fileNum;

    /**
     * 存储桶相对于命名空间的路径,如: dhy/private
     */
    private String path;

    /**
     * 创建时间
     */
    private LocalDateTime createTime;

    /**
     * 更新时间
     */
    private LocalDateTime updateTime;


    public static File zipDirIfNeeded(String bucket, String name, LocalFileProperty localFileProperty) {
        //判断目标文件是否存在,如果存在那么是否为目录
        return ZipUtil.zipIfNeeded(localFileProperty.getFilePathByOnlineUser(bucket,name), localFileProperty.getZipTempDir());
    }


    public void doDeleteFiles(LocalFileProperty localFileProperty) {
        FileUtil.deleteFile(localFileProperty.getBucketPath(name));
    }

    /**
     * @param bucketType 大于0都默认为读写
     */
    public void setBucketType(Integer bucketType) {
        this.bucketType = bucketType>0?1:0;
    }

    public void deleteCheck() {
        //当前用户只能删除自己创建的存储桶
        Assert.isTrue(UserThreadHolder.get().getId().equals(createBy),"无权删除该存储桶!");
        //如果删除的是默认桶,则抛出异常,default存储桶不可以被删除
        Assert.isTrue(!LocalFileProperty.DEFAULT_BUCKET.equals(name),"default存储桶不能被删除");
    }
}
